import router from '@/router'
import { defineStore } from 'pinia'
import {login,passVcode,updetePasd,roleList,delroleList,roletreeList,addRole,updroleList,updatadrole,fproleList,Cupdatarole} from '../api/axiosPlus.js'
import { ElMessage, ElMessageBox } from 'element-plus'

export const useCounterStore = defineStore('counter', {
  // 数据
    state: () => {
        return {
          //批量删除Id数组
          pldeleId:[],
          //分配用户角色数据  id
          assignRoleduixiang:[],
          assignRoleslistId:'',
          allCheckId:[],
          allCheckName:'',
          //所有用户信息
          allRoleName:[],
          //分配用户对话框是否显示
          assignRolesIsok:false,
          //分配用户数据清空
          assignRolesRef:'',
          //分配角色对话框数据
          fproleList:'',
          rolexgqxList:[],
          //角色类型
          options : [
            {
              value: '超级管理员',
              label: '超级管理员',
            },
            {
              value: '普通管理员',
              label: '普通管理员',
            },
           
          ],
          treecIds:[],
          treefIds:[],
          //编辑对话框是否显示
          updateIsok:false,
          //角色列表编辑对话框  清苦数据
          updateroleRef:'',
          //角色列表编辑对话框数据
          updateroleList:"",
          //修改角色d的权限List
          rolexgqxList:[],
          //清空添加角色表单
          RoleFroms:'',
          ////添加角色  角色操作权限  树形控件配置
          assroleTree:{
            value:'name',
            label: 'name',
          },
          roleTree:{
            children: 'children',
            label: 'name',
          },
           //添加角色  角色操作权限  树形控件数据
       roleqxList:[],
          //添加用户表单数据
          addRoleFrom:{
            name:'',
            roletype:'',
            nameactive:''
          },
          //默认数量
          pageSize:5,
          // 默认分页
          roleCurrentPage:1,
          activeName:'first',
            activeIndex :'/role',
            //用户列表数据
            roletableData:[],
            count: 10,
            formList:{
                name: '',
                pas:'',
                checked1:false
            },
            retrievePasList:{
                phone:'',
                Vcode:'',
                newPas:''
            },
            isOk:false,
            pasFromlist:'',
            rules: {
                name: [
                  { required: true, message: "请输入用户名", trigger: "blur" },
                  {
                     // 昵称格式：限16个字符，支持中英文、数字、减号或下划线
                    pattern: /^[a-zA-Z0-9]*$/,    //正则校验不用字符串
                    message: "请填写正确的用户名", trigger: "blur"
                  },
                  { min: 4, max: 16, message: '长度在6到16个字符之间' },
                ],
                pas:[
                    {required: true, message: "请输入密码", trigger: "blur"},
                    {
                        //密码不能有非法字符
                       pattern: /^[a-zA-Z0-9]*$/,    //正则校验不用字符串
                       message: "请填写正确的密码", trigger: "blur"
                     },
                     { min: 6, max: 16, message: '长度在6到16个字符之间' },
                ]
              }
        }
    },
    // 计算属性
    getters: {},
    // 方法
    actions: {
      //关闭用户分配对话框触发
      gbdialogs(){
        this.assignRoleduixiang=[]
        this.allCheckId=[]
      },
      //点击复选框
      CdjcheckBoxs(selection){
       console.log(selection)
       this.pldeleId=[]
       selection.forEach(item=>{
        console.log(item)
        this.pldeleId.push(item.rid)
       })
       console.log(this.pldeleId)
      },
      //批量删除
       pldeles(){
        console.log(this.pldeleId)
        if( this.pldeleId.length==0){
          ElMessage({
            type: 'success',
            message: '请选择需要删除的角色',
          })
        }else{
          ElMessageBox.confirm(
            '是否确认删除?',
            '温馨提示',
            {
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              type: 'warning',
            }
          )
            .then(async () => {
              console.log( this.pldeleId.join(','))
              let res =await delroleList({
                params:{
                  id:this.pldeleId.join(',')
                }
              })
              console.log(res)
           this.gitroleList()
           if(res.status == 201){
             ElMessage({
                type: 'success',
                message: res.message,
              })
           }else{
            ElMessage({
              type: 'error',
              message: res.message,
            })
           }
             
            })
            .catch(() => {
              ElMessage({
                type: 'info',
                message: '取消删除',
              })
            })
        }
       
      },
      //角色，用户 匹配的数据
       getaddoK(){
        let a= this.allRoleName.filter(item=>item.role===this.assignRoleslistId.rname)
        console.log(a[0])
        this.allCheckId.push(a[0].id)
        console.log(this.allCheckId)
        this.allCheckName=this.allCheckId
      },
        //分配角色对话框确点击复选框
      addSelect(){
        setTimeout(() => {
           console.log(this.allCheckName)
        }, 1000);
       
      },
      async getupdatarole(a){
        let hh =await  Cupdatarole({
          id:a[0].id,
          username:a[0].username,
          password:a[0].password,
          mobile:a[0].mobile,
          isDelete:a[0].isDelete,
          role: this.assignRoleslistId.rname,
          name:a[0].name,
          latelyLG:a[0].latelyLG,
          remarks:a[0].remarks,
          state:a[0].state,
          Department:a[0].Department,
        })
        console.log(hh)
        if(hh.status=200){
          ElMessage({
            type: 'success',
            message: hh.message,
          })
        }else{
          ElMessage({
            type: 'error',
            message: hh.message,
          })
        }
      },

       //分配角色对话框确认按钮
         qrassignRoles(){
        console.log(this.allCheckName)
        console.log(111);
         this.allCheckName.forEach (item=> {
          console.log(item);
          let a = this.allRoleName.filter(res=>{
           return res.id==item
          })
          console.log(a)
          console.log(this.assignRoleslistId.rname);
          this.getupdatarole(a)
        })
        // this.assignRolesRef.resetFields()
        // this.assignRolesIsok=false
       },
       //分配角色对话框取消按钮
       qxassignRoles(){
        this.assignRolesRef.resetFields()
        this.assignRolesIsok=false
       },
      //获取分配用户数据 分配用户按钮
      async getfproleList(e){
        console.log(e)
        console.log(1111);
        
        this.allCheckName=[]
        this.assignRolesIsok=true
        let asd =await fproleList({
           params:{
              pagenum:1,
              pagesize:100
          }
        })
        console.log(asd.result)
        this.allRoleName=asd.result
        this.allRoleName.forEach(item=>{
          this.assignRoleduixiang.push({
            value:item.id,
            label:item.name
          })

        })

          //id拿值
          const res =await updroleList({params:{
            id:e.rid
        }})
        console.log(res.data)
        this.assignRoleslistId = res.data[0]
        console.log(this.assignRoleslistId)
        console.log(1111);
        console.log( this.assignRoleduixiang);
        this.getaddoK()
      },
       //修改对话框确认按钮
       async updeteroleBtns(){
        console.log(this.updateroleList)
        console.log(this.treecIds.join(','))
        console.log(this.treefIds.join(','))
        let asd =await updatadrole({
          rname : this.updateroleList.rname,
          descri:this.updateroleList.descri,
          type:this.updateroleList.type,
          ft:this.treefIds.join(','),
          son:this.treecIds.join(','),
          id:this.updateroleList.rid
        })
        console.log(asd)
        if(asd.status==200){
          this.gitroleList()
          this.updateIsok=false
          this.updateroleRef.resetFields()
          ElMessage({
            type: 'success',
            message: asd.message,
          })
        }else(
          ElMessage({
            type: 'error',
            message: asd.message,
          })
        )
       },
      //获取修改角色的树形控件数据
     async updroletree(){
      let res =await roletreeList()
      this.rolexgqxList=res.arr
      console.log(this.rolexgqxList)
    },
       //修改对话框取消按钮
       roleUptqxisOks(){
        this.updateroleRef.resetFields()
        this.updateIsok=false
      },
      //角色修改按钮
      async updataRoleBtns(e){
        this.treecIds=''
        this.treefIds=''
        this.updroletree()
        this.updateIsok=true
       const res =await updroleList({params:{
           id:e.rid
       }})
       console.log(res)
       this.updateroleList=res.data[0]
       this.treecIds=this.updateroleList.son.split(',')
       this.treefIds=this.updateroleList.ft.split(',')
       console.log(this.updateroleList)
      },
       //获取树形控件所选节点数据
     currentChecks (nodeObj,SelectedObj){
           // console.log(nodeObj);
      console.log(SelectedObj)
      let a =[]
      let b =[]
      SelectedObj.checkedKeys.forEach(element => {
       console.log(element)
       if(element>=5){
         a.push(element)
       }else{
         b.push(element)
       }
      });
       b=[...b,...SelectedObj.halfCheckedKeys]
       this.treecIds=a
       this.treefIds=b
       console.log(this.treecIds,this.treefIds)
   
         },
      //获取添加角色的树形控件数据
     async getroletree(){
        let res =await roletreeList()
        this.roleqxList=res.arr
        console.log(this.roleqxList)
      },
      //用户列表删除
       delroleList(e){
     console.log(e)
     ElMessageBox.confirm(
      '是否确认删除该角色',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(async () => {
        const del =await delroleList({params:{
      id:e.rid
     }})
     this.gitroleList()
     console.log(del)
     if(del.status == 201){
       ElMessage({
          type: 'success',
          message: del.message,
        })
     }else{
      ElMessage({
        type: 'error',
        message: del.message,
      })
     }
       
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
     
      },
      //获取角色列表信息
     async gitroleList(){
        const role =await roleList({params:{
          pagenum:this.roleCurrentPage,
          pageSize:this.pageSize
        }})
      
        this.roletableData=role.result
        console.log(this.roletableData)
      },
      //退出添加角色页面事件
      tcBtns(){
        router.push('/role')
        this.activeName='first'
        this.RoleFroms.resetFields()
      },
      //确认添加角色
      async querBtns(){
        router.push('/role')
        this.activeName='first'
        let asd =await addRole({
            rname:this.addRoleFrom.name,
            descri:this.addRoleFrom.nameactive,
            type:this.addRoleFrom.roletype,
            ft:this.treefIds.join(','),
            son:this.treecIds.join(',')
        })
        if(asd.status==200){
          ElMessage({
            type: 'success',
            message: asd.message,
          })
        }else{
          ElMessage({
            type: 'error',
            message: asd.message,
          })
        }
        console.log(asd)
       this.RoleFroms.resetFields()
      },
      //添加角色   下一页
      nextye(){
        this.activeName='second'
      },
      //添加角色按钮事件
      goAddRoles(){
        router.push('/role/add')
      },
      //page-size 改变时触发
      handleSizeChange(val) {
        console.log(`${val} items per page`)
        this.pageSize=val
        console.log(this.pageSize)
      },
      //页码改变时触发
     handleCurrentChange  (val) {
        console.log(`current page: ${val}`)
        this.roleCurrentPage = val
        console.log(this.roleCurrentPage)
      },
        //修改密码界面取消按钮
        qxisOks(){
            this.isOk=false
            this.pasFromlist.resetFields();
        },
        //修改密码
    async updatePasd(){
        let res =await updetePasd({newpassword:this.retrievePasList.pas,mobile:this.retrievePasList.phone})
    console.log(res)
    if(res.status==200){
        this.isOk=false  
        ElMessage({
            message: res.message,
            type: 'success',
          })
          this.pasFromlist.resetFields();
    }else{
        ElMessage({
            message: res.message,
            type: 'error',
          })
    }
    },
        //修改密码验证码
       async pasVcodes(){
            let res =await passVcode()
            console.log(res)
            ElMessageBox.alert(res.msessage, '验证码')
        },
        getUserName(){
            if(localStorage.getItem('mdUser')==null){

            }else{
                 const user = JSON.parse(localStorage.getItem('mdUser'))
             console.log(user)
             this.formList.name = user.name
             this.formList.pas =user.pas
             this.formList.checked1 =user.checked1
            }
            
        },
        //登录事件
       async loginBtn(){
            let res = await login({username:this.formList.name,password:this.formList.pas})
          console.log(res.token)
          console.log(res);
          if(res.status==200){
           sessionStorage.setItem('token', JSON.stringify(res.token))
            router.push('./home')
            ElMessage({
                message: res.message,
                type: 'success',
              })
              let usera = ''
              if(!this.formList.checked1){
                 localStorage.setItem('mdUser',usera )
                 this.formList.pas=''
              localStorage.setItem('mdUser',JSON.stringify(this.formList) )
               let users = localStorage.getItem('mdUser')||[]
               console.log(users)
                // ft  son
               sessionStorage.setItem('uplus', JSON.stringify({
                ft: res.ft,
                son: res.son
               }))

              }else{
                localStorage.setItem('mdUser',usera )
              localStorage.setItem('mdUser',JSON.stringify(this.formList) )
               let users = localStorage.getItem('mdUser')||[]
               console.log(users)
              }
          }else{
            ElMessage({
                message: res.message,
                type: 'error',
              })
              this.formList.pas=''
          }
         
        },
        forgotPas(){

        }
    },
})
